package com.lzs.bootsafety.business.sys.controller;

import com.alibaba.fastjson.JSON;
import com.lzs.bootsafety.business.sys.entity.SysDept;
import com.lzs.bootsafety.business.sys.entity.SysDeptTree;
import com.lzs.bootsafety.business.sys.service.SysDeptService;
import com.lzs.bootsafety.common.base.controller.BaseController;
import com.lzs.bootsafety.common.util.DeptTree;
import com.lzs.bootsafety.common.util.Resu;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/sys/dept")
public class DeptController extends BaseController {
    @Autowired
    private SysDeptService sysDeptService;
    //下拉框树
    @GetMapping("/selectList")
    public Resu getDeptList(){
        List<SysDeptTree> deptTreeList=new ArrayList<>();
        List<SysDept> sysDeptList = sysDeptService.getSysDeptList(null);
        sysDeptList.forEach((sysDept)->{
            SysDeptTree sysDeptTree = new SysDeptTree();
            sysDeptTree.setId(sysDept.getDeptId());
            sysDeptTree.setLabel(sysDept.getName());
            sysDeptTree.setParentId(sysDept.getParentId());
            deptTreeList.add(sysDeptTree);
        });
        return Resu.suces().put("data",DeptTree.buildTrees(deptTreeList,(long)0));
    }
    @GetMapping("/list")
    @RequiresPermissions("sys:dept:list")
    public Resu list(@RequestParam("data") String  data){
        SysDept sysDept = JSON.parseObject(data,SysDept.class);
        List<SysDept> sysDepts = sysDeptService.getSysDeptList(sysDept);
        if(checkIsNull.objCheckIsNull(sysDept)){
            return Resu.suces().put("data",DeptTree.buildTree(sysDepts,(long)0));
        }else{
            return Resu.suces().put("data",sysDepts);
        }
    }
    @GetMapping("/info")
    @RequiresPermissions("sys:dept:info")
    public Resu info(Long deptId){
        SysDept sysDept = sysDeptService.selectDeptBydeptId(deptId);
        return Resu.suces().put("data",sysDept);
    }
    @PostMapping("/add")
    @RequiresPermissions("sys:dept:add")
    public Resu add(@RequestBody SysDept sysDept){
        sysDept.setCreatePeople(getUserName());
        sysDept.setCreateTime(new Date());
        int r = sysDeptService.addDept(sysDept);
        return respAdd(r);
    }
    @PutMapping("/modify")
    @RequiresPermissions("sys:dept:modify")
    public Resu modify(@RequestBody SysDept sysDept){
        sysDept.setUpdatePeople(getUserName());
        sysDept.setUpdateTime(new Date());
        int r = sysDeptService.updateDept(sysDept);
        return respudp(r);
    }
    @DeleteMapping("/del")
    @RequiresPermissions("sys:dept:del")
    public Resu del(Long deptId){
        int r = sysDeptService.delBydeptId(deptId);
        return respDel(r);
    }
}
